<?php
class Purchase_Loss extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
				# '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'purchase_loss',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}
	
	
/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}
	
/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */

	
	/**
	 * 创建采购损耗
	 * @param $purchase_loss 采购损耗信息
	 */	
	static function create($purchase_loss)
	{
		foreach ($purchase_loss as $pl)
		{
			$purchase_loss = new Purchase_Loss();
			$purchase_loss->product_basic_id = $pl['product_basic_id'];
			$purchase_loss->price = $pl['price'];
			$purchase_loss->quantity = $pl['quantity'];
			$purchase_loss->create_time = CURRENT_DATETIME;
			$purchase_loss->create_user_id = CURRENT_USER_ID;
			$purchase_loss->reason = $pl['reason'];
			$purchase_loss->save();
		}
		return array('ack' => SUCCESS, 'message' => '');
	}

	/**
	 * 编辑采购损耗
	 * @param $purchase_loss 采购损耗信息
	 */	
	static function edit($purchase_loss)
	{
		$judge_result = Purchase_Loss::judgeHandle($purchase_loss['id'], 'edit');
		if ($judge_result['ack'] == SUCCESS)
		{
			$purchase_loss_obj = Purchase_Loss::find('purchase_loss.id=?', $purchase_loss['id'])->getOne();
			$purchase_loss_obj->product_basic_id = $purchase_loss['product_basic_id'];
			$purchase_loss_obj->create_user_id = CURRENT_USER_ID;
			$purchase_loss_obj->price = $purchase_loss['price'];
			$purchase_loss_obj->quantity = $purchase_loss['quantity'];
			$purchase_loss_obj->reason = $purchase_loss['reason'];
			$purchase_loss_obj->save();
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	/**
	 * 删除采购损耗
	 * @param $id 采购损耗记录ID
	 */	
	static function delete($id)
	{
		$judge_result = Purchase_Loss::judgeHandle($id, 'delete');
		if ($judge_result['ack'] == SUCCESS)
		{
			Purchase_Loss::meta()->deleteWhere('id=?', $id);
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}

	/**
	 * 采购审核
	 * @param $id 采购损耗记录ID
	 */	
	static function purchaseAudit($id)
	{
		$judge_result = Purchase_Loss::judgeHandle($id, 'purchase audit');
		if ($judge_result['ack'] == SUCCESS)
		{
			$purchase_loss = Purchase_Loss::find('id=?', $id)->getOne();
			$purchase_loss->purchase_audit = Q::ini('custom_flag/purchase_loss_purchase_audit/audited/value');
			$purchase_loss->purchase_audit_user_id = CURRENT_USER_ID;
			$purchase_loss->purchase_audit_time = CURRENT_DATETIME;
			$purchase_loss->save();
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	/**
	 * 财务审核
	 * @param $ids 采购损耗记录ID
	 */	
	static function financeAudit($ids)
	{
		$message = array();
		foreach ($ids as $key => $id)
		{
			$judge_result = Purchase_Loss::judgeHandle($id, 'finance audit');
			if ($judge_result['ack'] == SUCCESS)
			{
				$purchase_loss = Purchase_Loss::find('id=?', $id)->getOne();
				$purchase_loss->finance_audit = Q::ini('custom_flag/purchase_loss_finance_audit/audited/value');
				$purchase_loss->finance_audit_user_id = CURRENT_USER_ID;
				$purchase_loss->finance_audit_time = CURRENT_DATETIME;
				$purchase_loss->save();
			}
			else
			{
				$message[] = 'No.' . ($key + 1) . ' ' . $judge_result['message'];
			}
		}
		if ($message)
		{
			return array('ack' => FAILURE, 'message' => implode(',', $message));
		}
		else
		{
			return array('ack' => SUCCESS, 'message' => '');
		}
	}
	
	/**
	 * 判断是否满足操作条件
	 * @param $id 采购损耗记录ID
	 * @param $handle_type 操作类型
	 */	
	static function judgeHandle($id, $handle_type)
	{
		$purchase_loss = Purchase_Loss::find('id=?', $id)->asArray()->getOne();
		if ($purchase_loss['id'])
		{
			switch ($handle_type)
			{
				case 'finance audit':
					return (($purchase_loss['purchase_audit'] == Q::ini('custom_flag/purchase_loss_purchase_audit/audited/value') && $purchase_loss['finance_audit'] == Q::ini('custom_flag/purchase_loss_finance_audit/unaudited/value')) ? array('ack' => SUCCESS) : array('ack' => FAILURE, 'message' => 'cannot ' . $handle_type));
				default:
					return (($purchase_loss['purchase_audit'] == Q::ini('custom_flag/purchase_loss_purchase_audit/unaudited/value') && $purchase_loss['finance_audit'] == Q::ini('custom_flag/purchase_loss_finance_audit/unaudited/value')) ? array('ack' => SUCCESS) : array('ack' => FAILURE, 'message' => 'cannot ' . $handle_type));
			}
		}
	}
	
	/**
	 * 按条件搜索采购损耗记录
	 * @param $condition 条件
	 * @param $cp 当前页
	 * @param $ps 每页大小
	 */
	static function search($condition, $cp, $ps)
	{
		$columns = array(
			'purchase_loss.*',
			'user.name as create_user_name',
			'product_basic.number,product_basic.name'
		);
		$where = Purchase_Loss::buildSearchWhere($condition);
		if ($cp == 0 && $ps == 0)
		{
			$select = Purchase_Loss::find($where)
				->joinLeft('user', '', 'user.id=purchase_loss.create_user_id')
				->joinLeft('product_basic', '', 'product_basic.id=purchase_loss.product_basic_id')
				->order('purchase_loss.create_time desc')->setColumns($columns);
			$pagination = array();
		}
		else
		{
			$select = Purchase_Loss::find($where)
				->joinleft('user', '', 'user.id=purchase_loss.create_user_id')
				->joinLeft('product_basic', '', 'product_basic.id=purchase_loss.product_basic_id')
				->order('purchase_loss.create_time desc')->setColumns($columns)->limitPage($cp, $ps);
			$pagination = $select->getPagination();
		}
		$purchase_loss = $select->asArray()->getAll();
		return array(
			'ack' => SUCCESS,
			'message' => '',
			'data' => $purchase_loss,
			'pagination' => $pagination
		);
	}
	
	/**
	 * 组装搜索条件
	 * @param $condition 条件数组
	 */
	static function buildSearchWhere($condition)
	{
		$where = '1';
		if (isset($condition['limit']) && $condition['limit'])
		{
			$where .= ' and purchase_loss.create_user_id=' . CURRENT_USER_ID;
		}
		if (! empty($condition['begin_create_time']))
		{
			$where .= ' and purchase_loss.create_time>=\'' . $condition['begin_create_time'] . '\'';
		}
		if (! empty($condition['end_create_time']))
		{
			$where .= ' and purchase_loss.create_time<=\'' . $condition['end_create_time'] . ' 23:59:59\'';
		}
		if (! empty($condition['begin_finance_audit_time']))
		{
			$where .= ' and purchase_loss.finance_audit_time>=\'' . $condition['begin_finance_audit_time'] . '\'';
		}
		if (! empty($condition['end_finance_audit_time']))
		{
			$where .= ' and purchase_loss.finance_audit_time<=\'' . $condition['end_finance_audit_time'] . '\'';
		}
		if (! empty($condition['product_basic_number']))
		{
			$where .= ' and product_basic.number=' . $condition['product_basic_number'];
		}
		if (! empty($condition['create_user_id']))
		{
			$where .= ' and purchase_loss.create_user_id=' . $condition['create_user_id'];
		}
		if ( isset($condition['purchase_audit']))
		{
			$purchase_audit_filter = '0';
			foreach (Q::ini('custom_flag/purchase_loss_purchase_audit') as $fa)
			{
				if (isset($condition['purchase_audit'][$fa['value']]) && $condition['purchase_audit'][$fa['value']] == $fa['value'])
				{
					$purchase_audit_filter .= ' or purchase_loss.purchase_audit=' . $fa['value'];
				}
			}
			$where .= ' and (' . $purchase_audit_filter . ')';
		}
		if ( isset($condition['finance_audit']))
		{
			$finance_audit_filter = '0';
			foreach (Q::ini('custom_flag/purchase_loss_finance_audit') as $fa)
			{
				if (isset($condition['finance_audit'][$fa['value']]) && $condition['finance_audit'][$fa['value']] == $fa['value'])
				{
					$finance_audit_filter .= ' or purchase_loss.finance_audit=' . $fa['value'];
				}
			}
			$where .= ' and (' . $finance_audit_filter . ')';
		}
		if (! empty($condition['quantity']))
		{
			$where .= ' and purchase_loss.quantity>=' . $condition['quantity'];
		}
		return $where;
	}
}